# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : orderlines_save_view.py
# Time       ：2023/9/19 16:29
# Author     ：YangYong
# version    ：python 3.10
# Description：保存流程图数据
"""
from datetime import datetime

from flask import request
from flask_restx import fields

from apis.orderlines import orderlines_ns
from apis.orderlines.models import Task, Process
from apis.orderlines.utils.flow_save_utils import FlowSaveUtils
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel
from public.base_view import AbstractView

orderlines_save_model = {'process_id': fields.String()}
orderlines_save_marshal = MarshalModel('save', orderlines_ns)


class OrderlinesSaveView(AbstractView):
    url = '/save'

    def __init__(self, *args, **kwargs):
        super(OrderlinesSaveView, self).__init__(*args, **kwargs)
        self.form_data = request.json
        self.process_id = self.form_data.get('process_id')
        self.flow_save_util = FlowSaveUtils(self.process_id)
        self.is_logger = True

    @handle_api_error()
    @orderlines_ns.expect(orderlines_save_marshal.detail_request(orderlines_save_model))
    @orderlines_ns.marshal_with(orderlines_save_marshal.detail_response())
    def post(self):
        """保存流程"""
        task_nodes = self.flow_save_util.generate_task_node()
        for index, task_node in enumerate(task_nodes):
            update_data = {
                'prev_id': task_node.get('prev_id'),
                'next_id': task_node.get('next_id'),
                'task_index_id': index + 1
            }
            if task_node.get('type') == 'group-node' and task_node.get('children'):
                update_data['method_kwargs'] = {'group_ids': task_node.get('children')}
            # 修改任务信息
            with db.auto_commit():
                db.session.query(Task).filter(
                    Task.task_id == task_node.get('task_id'),
                    Task.active == 1
                ).update(update_data)
            # 修改流程信息
            with db.auto_commit():
                db.session.query(Process).filter(
                    Process.process_id == self.process_id
                ).update({'update_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')})
                db.session.commit()
        return generate_response(message='流程保存成功')
